<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Village extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 获取村落商品列表
	 */
	public function getVillageGoodsList(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'village_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['a.village_id', 'eq', $in['village_id']];
				if( isset($in['create_date']) ) $where[] = ['b.create_date', 'between', $in['create_date']];
				if( isset($in['name']) ) $where[] = ['b.name', 'like', '%' . trim($in['name']) . '%'];
				
				if( isset($in['className']) && !empty($in['className']) ){
					$classWhere[] = ['name', 'like', '%'.trim($in['className']).'%'];
					$class = Db::table("gd_classification") -> where($classWhere) -> select();
					if( empty($class) ) returnResults(['code'=>'99999']);
					$where[] = ['b.class_id1|b.class_id2|b.class_id3', 'in', array_column($class, 'id')];
				}
				$field = ['b.*', 'a.goods_id'];
				$data = Db::table("gd_village_goods")-> alias('a') -> join('gd_goods b', 'a.goods_id = b.id', 'left') -> field($field) -> where($where) -> order("a.id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_village_goods")-> alias('a') -> join('gd_goods b', 'a.goods_id = b.id', 'left') -> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$data[$k]['totalInventory'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['goods_id'], 'is_delete'=>0]) -> sum("num");
						$data[$k]['min_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['goods_id'], 'is_delete'=>0]) -> min("min_price_protection");
						$data[$k]['max_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['goods_id'], 'is_delete'=>0]) -> max("max_price_protection");
						$data[$k]['min_price'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['goods_id'], 'is_delete'=>0]) -> min("price");
						if( !empty($v['class_id1']) ) $data[$k]['className1'] = Db::table("gd_classification") -> where(['id'=>$v['class_id1']]) -> find()['name'];
						if( !empty($v['class_id2']) ) $data[$k]['clsssName2'] = Db::table("gd_classification") -> where(['id'=>$v['class_id2']]) -> find()['name'];
						if( !empty($v['class_id3']) ) $data[$k]['clsssName3'] = Db::table("gd_classification") -> where(['id'=>$v['class_id3']]) -> find()['name'];
						$data[$k]['className'] = [];
						if( isset($data[$k]['className1']) ) $data[$k]['className'][] = $data[$k]['className1'];
						if( isset($data[$k]['clsssName2']) ) $data[$k]['className'][] = $data[$k]['clsssName2'];
						if( isset($data[$k]['clsssName3']) ) $data[$k]['className'][] = $data[$k]['clsssName3'];
						$data[$k]['className'] = implode(',', $data[$k]['className']);
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取村落商品列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量移除村落商品
	 */
	public function batchDeleteVillageGoods(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'village_id', 'goods_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['village_id', 'eq', $in['village_id']];
				if( isset($in['id']) ) $where[] = ['id', 'in', $in['id']];
				if( isset($in['goods_id']) ) $where[] = ['goods_id', 'in', $in['goods_id']];
				
				$oldData = Db::table("gd_village_goods") -> where($where) -> select();
				
				if( !empty($oldData) ){
					$delRes = Db::table("gd_village_goods") -> where($where) -> delete();
					if( !$delRes ) returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量移除村落商品',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量绑定商品
	 */
	public function batchBindVillageGoods(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'village_id', 'goods_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['village_id', 'eq', $in['village_id']];
				
				$oldData = Db::table("gd_village_goods") -> where($where) -> select();
				if( !empty($oldData) ){
					foreach ($in['goods_id'] as $k => $v) {
						foreach ($oldData as $kk => $vv) {
							if( $v == $vv['goods_id'] ) unset($in['goods_id'][$k]);
						}
					}
				}
				
				if( !empty($in['goods_id']) ){
					$newData = [];
					foreach ($in['goods_id'] as $k => $v) {
						$newData[$k]['village_id'] = $in['village_id'];
						$newData[$k]['goods_id'] = $v;
						$newData[$k]['create_user_id'] = $in['user_id'];
						$newData[$k]['create_user_name'] = $userInfo['info']['nickname'];
						$newData[$k]['create_user_type'] = $userInfo['info']['type'];
						$newData[$k]['create_date'] = date("Y-m-d H:i:s", time());
					}
					$res = Db::table("gd_village_goods") -> insertAll($newData);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量绑定村落商品',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	
	/**
	 * 批量删除
	 */
	public function batchEditIsDelete(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				
				$oldData = Db::table("gd_village") -> where($where) -> select();
				
				Db::startTrans();
				foreach ($oldData as $k => $v) {
					$save['is_delete'] = 1;
					$save = filterArr($save, array_keys($save), $v);
					if( !empty($save) ){
						$re = Db::table("gd_village") -> where(['id'=>$v['id']]) -> update($save);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
						}
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量删除村落',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				
				$data = Db::table("gd_village") -> where($where) -> find();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取村落详情',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['name']) ) $where[] = ['name', 'like', '%' . trim($in['name']) . '%'];
				if( isset($in['is_delete']) ) $where[] = ['is_delete', 'eq', trim($in['is_delete'])];
				
				$data = Db::table("gd_village") -> where($where) -> order("sort asc") -> limit($start, $num) -> select();
				$count = Db::table("gd_village") -> where($where) -> count();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取村落列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_village") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
				$save = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$save[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				$save = filterArr($save, array_keys($save), $oldData);

				Db::startTrans();
//				排序字段存在
				if( isset($save['sort']) ){
					$all = Db::table("gd_village") -> select();
					if( !empty($all) ){
//						判断是否重叠
						foreach($all as $k => $v){
							if( $save['sort'] > $v['sort'] ) {
								unset($all[$k]);
							}else{
//								重叠，后面的数据全部往后移动一位
								$incRe = Db::table("gd_village") -> where(['id'=>$v['id']]) -> setInc('sort', 1);
								if( !$incRe ) {
									Db::rollback();
									returnResults2('-1', '变更排序失败,请联系管理员');
								}
							}
						}
					}
				}else{
//					排序字段不存在，查询已有最大的排序值
//					$maxSort = Db::table("gd_classification") -> max("sort");
//					Db::commit();
				}

				if( !empty($save) ){
					$re = Db::table("gd_village") -> where($where) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑村落',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 新增
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
					$newData['create_user_id'] = $in['user_id'];
					$newData['create_user_name'] = $userInfo['info']['nickname'];
					$newData['create_user_type'] = $userInfo['info']['type'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
				}

				Db::startTrans();
//				排序字段存在
				if( isset($newData['sort']) ){
					$all = Db::table("gd_village") -> select();
					if( !empty($all) ){
//						判断是否重叠
						foreach($all as $k => $v){
							if( $newData['sort'] > $v['sort'] ) {
								unset($all[$k]);
							}else{
//								重叠，后面的数据全部往后移动一位
								$incRe = Db::table("gd_village") -> where(['id'=>$v['id']]) -> setInc('sort', 1);
								if( !$incRe ) {
									Db::rollback();
									returnResults2('-1', '变更排序失败,请联系管理员');
								}
							}
						}
					}
				}else{
//					排序字段不存在，查询已有最大的排序值
//					$maxSort = Db::table("gd_classification") -> max("sort");
				}

				$newId1 = Db::table("gd_village") -> insertGetId($newData);
				if( !$newId1 ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增村落',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>